<?php

namespace frontend\controllers\restful;

use common\models\Order;
use Yii;
use yii\rest\Controller;

class OrderController extends Controller
{

    public function actionIndex()
    {
    }


    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate()
    {
        /**
         * 3: //数组索引，与product_id等值
         * //产品信息对象
         * {
         *  id:3  --产品id
         *  product_name:" 馒头" //产品名称
         *  product_price:"2.00" //产品价格
         *  quantity:8 //产品数量
         * }
         ***完整格式如下
         * 1: {id: 1, product_name: " 肉包子", product_price: "3.00", quantity: 1}
         * 2: {id: 2, product_name: " 菜包子", product_price: "1.00", quantity: 1}
         * ...
        */
        $cart = Yii::$app->request->getBodyParams();
        if($cart){
            $res['data'] = $order = Order::add($cart);
            $res['status']='1';

            //发送微信文本卡片消息
            $msgDescription ='';
            $msgDescription .= "<div class=\"gray\">订单编号：".$order['order_no']."</div>";
            foreach ($order['orderProducts'] as $orderProduct){
                $msgDescription .= "<div class=\"normal\">{$orderProduct['product_name']}: x ".$orderProduct['quantity'].' = ￥'.$orderProduct['total']."</div>";
            }
            $msgDescription .= "<div class=\"highlight\">订单金额： ￥".$order['total']." 元</div>";
            $msgType = 'textcard';
            $msgBody = [
                'title'=>"下单成功通知",
                'description'=>$msgDescription,
                'url'=>'http://www.baidu.com',
                'btntext'=>'查看详情',
                ];
            $toUsers = [Yii::$app->user->identity->cwx_userid];
            $res['data']['cwx_res'] = Yii::$app->cwx->CWXMessage->send($msgBody,$msgType,$toUsers);
        }else
            $res['status']='0';
        return $res;
    }

    /**
     * @param $action
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action)
    {
        if(Yii::$app->user->isGuest)
        {
            //101表示未登录
            $res = ['status'=>'101'];
            echo json_encode($res);
            return false;
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
}